package indigo.ueditor;

import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.util.Map;
import java.util.Set;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.common.io.CharStreams;

public class JsonConfigReader {
	private static final ObjectMapper objectMapper = new ObjectMapper();

	private final JsonNode config;

	public JsonConfigReader(InputStream stream) throws IOException {
		Reader textReader = new InputStreamReader(stream, StandardCharsets.UTF_8);
		String textContent = CharStreams.toString(textReader);
		config = objectMapper.readTree(textContent.replaceAll("/\\*[\\s\\S]*?\\*/", ""));
	}

	public Map<String, Object> getAll() {
		return objectMapper.convertValue(config, new TypeReference<Map<String, Object>>() {});
	}

	public String getString(String path, String defaultValue) {
		return config.path(path).asText(defaultValue);
	}

	public int getInt(String path, int defaultValue) {
		return config.path(path).asInt(defaultValue);
	}

	public long getLong(String path, long defaultValue) {
		return config.path(path).asLong(defaultValue);
	}

	public Set<String> getStringSet(String path) {
		Set<String> set = Sets.newHashSet();
		for (JsonNode node : config.path(path)) {
			set.add(node.asText());
		}
		return ImmutableSet.copyOf(set);
	}
}
